import { defineComponent, ref, onMounted, onUnmounted } from 'vue'
import './index.module.scss';

export default defineComponent({
  name: 'AudioWaveform',
  props: {
    videoElement: {
      type: HTMLVideoElement,
      default: null
    },
    waveformColor: {
      type: String,
      default: '#FFAE0D'
    },
    height: {
      type: Number,
      default: 60
    }
  },
  setup(props) {
    // 音频波线图
    const waveformCanvas = ref<HTMLCanvasElement | null>(null);
    const audioContext = ref<AudioContext | null>(null);
    const analyser = ref<AnalyserNode | null>(null);
    const source = ref<MediaElementAudioSourceNode | null>(null);
    const animationFrameId = ref<number | null>(null);
    // 初始化音频分析器
    const initAudioAnalyser = () => {
      if (!props.videoElement || audioContext.value) return;
      try {
        // 创建音频上下文
        const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
        audioContext.value = new AudioContext();
        // 创建分析器节点
        analyser.value = audioContext.value.createAnalyser();
        analyser.value.fftSize = 256;
        // 连接视频元素到分析器
        source.value = audioContext.value.createMediaElementSource(props.videoElement);
        source.value.connect(analyser.value);
        analyser.value.connect(audioContext.value.destination);
        // 开始绘制波形
        drawRealTimeWaveform();
      } catch (error) {
        console.error('初始化音频分析器失败:', error);
      }
    };
    // 绘制实时波形
    const drawRealTimeWaveform = () => {
      if (!analyser.value || !waveformCanvas.value) return;
      const canvas = waveformCanvas.value;
      const ctx = canvas.getContext('2d');
      if (!ctx) return;
      const width = canvas.width;
      const height = canvas.height;
      const bufferLength = analyser.value.frequencyBinCount;
      const dataArray = new Uint8Array(bufferLength);
      analyser.value.getByteTimeDomainData(dataArray);
      ctx.clearRect(0, 0, width, height);
      ctx.lineWidth = 2;
      ctx.strokeStyle = props.waveformColor;
      ctx.beginPath();
      const sliceWidth = width / bufferLength;
      let x = 0;
      // 关键修改：增加垂直缩放系数（1.5倍示例）
      const verticalScale = 5; // 调整这个值控制波形高度
      for (let i = 0; i < bufferLength; i++) {
        const v = (dataArray[i] / 128.0 - 1) * verticalScale; // 修改计算公式
        const y = (v + 1) * (height / 2); // 调整后的Y坐标
        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
        x += sliceWidth;
      }
      ctx.stroke();
      animationFrameId.value = requestAnimationFrame(drawRealTimeWaveform);
    };
    const initAudioWithRetry = async() => {
      try {
        if (audioContext.value?.state === 'suspended') {
          await audioContext.value.resume();
        }
        initAudioAnalyser();
      } catch (error) {
        console.warn('音频初始化失败，等待用户交互后重试...');
        // 可以在这里显示提示，要求用户点击
      }
    };
    onMounted(() => {
      props.videoElement?.addEventListener('play', initAudioWithRetry)
    })
    onUnmounted(() => {
      // 清理时断开所有连接
      if (source.value && analyser.value) {
        source.value.disconnect();
        analyser.value.disconnect();
      }
      if (audioContext.value?.state !== 'closed') {
        audioContext.value?.close();
      }
    });
    return () => (
      <div
        class='waveform-container'
        style={{
          height: props.height + 'px'
        }}
      >
        <canvas
          ref={waveformCanvas}
          class='waveform-canvas'
          height={props.height}
        />
      </div>
    )
  }
})
